<template>
    <div>
        <!-- 面包屑导航栏 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRole">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList" border stripe>
                <!-- 添加可展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bd-bottom',index == 0 ? 'bd-top' : '','vcenter']" v-for="(item,index) in scope.row.children" :key="item.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[index2 == 0 ? '' : 'bd-top','vcenter']" v-for="(secondItem,index2) in item.children" :key="secondItem.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,secondItem.id)">{{secondItem.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>                                        
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag v-for="thirdItem in secondItem.children" :key="thirdItem.id" type="warning" closable @close="removeRightById(scope.row,thirdItem.id)">{{thirdItem.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!-- <pre>{{scope.row}}</pre> -->
                    </template>
                </el-table-column>
                <!-- 添加索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setDialogVisible" width="50%">
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="40%" @close="addRoleClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRoles">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data: function() {
        return {
            rolesList: [],
            setDialogVisible: false,
            rightsList: [],
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            defKeys: [],
            roleId: '',
            addRoleDialogVisible: false,
            addForm: {
                roleName: '',
                roleDesc: ''
            },
            addFormRules:{
                roleName: [
                    {
                        required: true,
                        message: "请输入角色名称",
                        trigger: "blur"
                    },
                    {
                        min: 3,
                        max: 8,
                        message: "长度在 3 到 8 个字符",
                        trigger: "blur"
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: "请输入角色描述",
                        trigger: "blur"
                    },
                    {
                        min: 6,
                        max: 20,
                        message: "长度在 6 到 20 个字符",
                        trigger: "blur"
                    }
                ],
            }
        };
    },
    created: function() {
        this.getRolesList();
    },
    methods: {
        getRolesList: async function() {
            const { data: res } = await this.$http.get("roles");
            if (res.meta.status != 200)
                return this.$message.error("获取角色列表失败");
            this.rolesList = res.data;
            console.log(this.rolesList);
        },
        removeRightById: async function(role,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err);
            if(confirmResult != 'confirm') return this.$message.info('已取消删除');
            const {data : res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
            if(res.meta.status != 200) return this.$message.errror('权限删除失败');
            role.children = res.data;
        },
        showDialog: async function(role){
            this.roleId = role.id;
            const {data : res} = await this.$http.get('rights/tree');
            if(res.meta.status != 200) return this.$message.error('获取权限列表失败')
            this.rightsList = res.data;
            // console.log(this.rightsList)
            this.defKeys = [];
            //利用递归获取三级权限的id
            this.getLeafKeys(role,this.defKeys);
            this.setDialogVisible = true;
        },
        getLeafKeys(node,arr){
            if(!node.children) return arr.push(node.id);
            node.children.forEach(item => {
                this.getLeafKeys(item,arr);
            });
        },
        async allotRights(){
            // console.log(this.$refs.treeRef)
            const keys = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()];
            // console.log(keys);
            const idStr = keys.join(',');
            const {data : res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr});
            if(res.meta.status != 200) return this.$message.error('权限分配失败');
            this.$message.success('权限分配成功');
            this.getRolesList();
            this.setDialogVisible = false;
        },
        addRole(){
            this.addRoleDialogVisible = true;
        },
        allotRoles(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return this.$message.error('请输入合法的参数');
                const {data : res} = await this.$http.post('roles',this.addForm);
                if(res.meta.status != 201) return this.$message.error('添加角色失败');
                this.$message.success('添加角色成功');
                this.getRolesList();
                this.addRoleDialogVisible = false;
            })
        },
        addRoleClosed(){
            this.$refs.addFormRef.resetFields();
        }
    }
};
</script>
<style lang="less" scoped>
    .el-tag {
        margin: 7px;
    }
    .bd-top {
        border-top: 1px solid #eee;
    }
    .bd-bottom {
        border-bottom: 1px solid #eee;
    }
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>